package com.cloudpolice.equipment.unit;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tool.RedisAction;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 梁昊
 * @date 2019/12/3
 * @function
 * @editLog
 */
@Component
public class RedisOperator {
    @Autowired
    RedisAction redisAction;

    /**
     * 生成用户AccessToken
     *
     * @param systemId    主系统ID
     * @param sn       用户ID
     * @param useType     用户类型
     * @param clientType  客户端类型
     * @param isAutoAgain 是否自动续期
     * @return
     */
    public String writeIntoToken(String systemId, String sn, String useType, String clientType, boolean isAutoAgain) {
        String keyName = String.format("%s%s%s:%s", systemId, clientType, useType, sn);
        try {
            String accessToken = redisAction.getValue(keyName);
            if (accessToken == null) {
                accessToken = UUID.randomUUID().toString().replace("-", "");
                isAutoAgain = true;
            }
            if (isAutoAgain) {
                redisAction.saveKeyAndValue(keyName, accessToken, 1L, TimeUnit.DAYS);
            }
            return accessToken;
        } catch (Exception e) {
            throw e;
        }
    }
}
